package com.wyt.common.file.image;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

/**
 * @ClassName ImageOperationUtil
 * @Description: 图片处理工具类，注意前7个方法是对象方法，后面的方法是类方法，使用时要注意下
 * @Author wangyongtao
 * @Date 2021/7/25 12:03
 * @Version 1.0
 **/
public class ImageOperationUtil {

    private Font font = new Font("宋体",Font.PLAIN,12);

    private Graphics2D graphics2D = null;

    private int fontSize = 0;

    private int x = 0;

    private int y = 0;

    /**
     * 1、导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgPath){
        try {
            return ImageIO.read(new File(imgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 2、导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgUrl){
        try {
            URL url = new URL(imgUrl);
            return ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 3、生成新图片到本地
     */
    public void writeImageLocal(String newImgPath,BufferedImage image){
        if (newImgPath!=null && image!=null){
            File outputFile = new File(newImgPath);
            try {
                ImageIO.write(image,"jpg",outputFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 4、设定文字的字体等
     */
    public void setFont(String fontStyle,int fontSize){
        this.fontSize = fontSize;
        this.font = new Font(fontStyle,Font.PLAIN,fontSize);
    }

    /**
     * 5、修改图片、返回修改后的图片缓冲区（只输出一行文本）
     */
    public BufferedImage modifyImage(BufferedImage image,Object content,int x,int y){
        int w = image.getWidth();
        int h = image.getHeight();
        graphics2D = image.createGraphics();
        graphics2D.setBackground(Color.WHITE);
        //设置字体颜色
        graphics2D.setColor(Color.ORANGE);
        if (this.font!=null){
            graphics2D.setFont(this.font);
        }
        //验证输出位置的纵坐标与横坐标
        if (x>=h||y>=w){
            this.x = h-this.fontSize+2;
            this.y = w;
        }else {
            this.x = x;
            this.y = y;
        }
        if (content!=null){
            graphics2D.drawString(content.toString(),this.x,this.y);
        }
        graphics2D.dispose();
        return image;
    }

    /**
     * 6、修改图片、返回修改后的图片缓冲区（输出多个文本段）xory：true表示将内容在一行中输出，false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage image,Object[] contents,int x,int y,boolean xory) {
        int w = image.getWidth();
        int h = image.getHeight();
        graphics2D = image.createGraphics();
        graphics2D.setBackground(Color.WHITE);
        //设置字体颜色
        graphics2D.setColor(Color.ORANGE);
        if (this.font != null) {
            graphics2D.setFont(this.font);
        }
        //验证输出位置的纵坐标与横坐标
        if (x >= h || y >= w) {
            this.x = h - this.fontSize + 2;
            this.y = w;
        } else {
            this.x = x;
            this.y = y;
        }
        if (contents != null) {
            int arrLen = contents.length;
            if (xory) {
                for (int i = 0; i < arrLen; i++) {
                    graphics2D.drawString(contents[i].toString(), this.x, this.y);
                    //重新计算文本输出位置
                    this.x += contents[i].toString().length() * this.fontSize / 2 + 5;
                }
            } else {
                for (int i = 0; i < arrLen; i++) {
                    graphics2D.drawString(contents[i].toString(), this.x, this.y);
                    //重新计算文本输出位置
                    this.y += this.fontSize + 2;
                }
            }
        }
        graphics2D.dispose();
        return image;
    }

    /**
     * 7、将两张图片合成一张图片(覆盖式合并，即把image1覆盖在image2之上)
     *
     */
    public BufferedImage coverImagetogeter(BufferedImage image1,BufferedImage image2){
        int w = image1.getWidth();
        int h = image2.getHeight();

        graphics2D = image2.createGraphics();
        graphics2D.drawImage(image1,100,20,w,h,null);
        graphics2D.dispose();

        return image2;
    }

    /**
     * 8、截图方法
     * srcFile 源图片
     * targetFile截好后图片全名
     * startXAxis 开始截取位置横坐标
     * startYAxis开始截图位置纵坐标
     * width截取的长
     * hight截取的高
     */
    public static void cutImage(String srcFile, String targetFile, int startXAxis, int startYAxis, int width, int hight) {
        //1、获取图片读入器
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = readers.next();
        //2、获取图片读入流
        InputStream source = null;
        ImageInputStream iis = null;
        try {
            source = new FileInputStream(srcFile);
            iis = ImageIO.createImageInputStream(source);
        } catch (Exception e) {
            System.out.println("获取图片流失败");
        }
        reader.setInput(iis, true);
        //3、图片参数对象
        ImageReadParam param = reader.getDefaultReadParam();
        Rectangle rect = new Rectangle(startXAxis, startYAxis, width, hight);
        param.setSourceRegion(rect);
        BufferedImage bi = null;
        try {
            bi = reader.read(0, param);
            ImageIO.write(bi, targetFile.split("\\.")[1], new File(targetFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 9、图片拼接方法（注意：必须两张图片的长宽一致）
     *
     * @param files      要拼接的文件列表
     * @param type       拼接的类型：1表示横向拼接，2表示纵向拼接
     * @param targetFile
     */
    public static void mergeImage(String[] files, int type, String targetFile) {
        int len = files.length;
        if (len < 1) {
            throw new RuntimeException("图片数量小于1");
        }
        File[] src = new File[len];
        BufferedImage[] images = new BufferedImage[len];
        int[][] imgArray = new int[len][];
        int width = 0;
        int height = 0;
        for (int i = 0; i < len; i++) {
            src[i] = new File(files[i]);
            try {
                images[i] = ImageIO.read(src[i]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            width = images[i].getWidth();
            height = images[i].getHeight();
            imgArray[i] = new int[width * height];
            imgArray[i] = images[i].getRGB(0, 0, width, height, imgArray[i], 0, width);
        }
        int newHeight = 0;
        int newWidth = 0;
        //根据type设置，对图片进行横向或纵向拼接
        for (int i = 0; i < images.length; i++) {
            if (type == 1) {
                newHeight = newHeight > images[i].getHeight() ? newHeight : images[i].getHeight();
                newWidth += images[i].getWidth();
            } else if (type == 2) {
                newWidth = newWidth > images[i].getWidth() ? newWidth : images[i].getWidth();
                newHeight += images[i].getHeight();
            }
        }
        if (type == 1 && newWidth < 1) {
            return;
        }
        if (type == 2 && newHeight < 1) {
            return;
        }
        //生成新的图片
        BufferedImage imageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        int height_i = 0;
        int width_i = 0;
        for (int i = 0; i < images.length; i++) {
            if (type == 1) {
                imageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, imgArray[i], 0,
                        images[i].getWidth());
                width_i += images[i].getWidth();
            } else if (type == 2) {
                imageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), imgArray[i], 0, newWidth);
                height_i += images[i].getHeight();
            }
        }
        //输出想要的图片
        try {
            ImageIO.write(imageNew, targetFile.split("\\.")[1], new File(targetFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 10、将小图片贴到大图片形成一张图（合并）
     *
     * @param bigPath
     * @param smallPath
     * @param outFile
     */
    public static void overlapImage(String bigPath, String smallPath, String outFile) {
        try {
            BufferedImage big = ImageIO.read(new File(bigPath));
            BufferedImage small = ImageIO.read(new File(smallPath));
            Graphics2D g = big.createGraphics();
            int x = (big.getWidth() - small.getWidth()) / 2;
            int y = (big.getHeight() - small.getHeight()) / 2;
            g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
            g.dispose();
            ImageIO.write(big, outFile.split("\\.")[1], new File(outFile));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}